<template>
  <div class="healthInfo padding_20">
    <el-input v-model="param.searchCondition"
              placeholder="请输入标题"
              class="w-200"
              clearable
              @clear="handleQuery"></el-input>
    <el-button @click="handleQuery"
               type="primary">查 询
    </el-button>
    <el-button @click="handleAdd"
               type="primary">新 增
    </el-button>
    <el-table stripe
              :data="tableData"
              style="width: 100%"
              class="mt-20"
              border>
      <el-table-column align="center"
                       type="index"
                       min-width="20">
      </el-table-column>
      <el-table-column align="center"
                       prop="title"
                       label="标题"
                       min-width="500">
      </el-table-column>
      <el-table-column align="center"
                       prop="sourceName"
                       label="作者/来源"
                       min-width="150">
      </el-table-column>
      <el-table-column align="center"
                       label="资讯类型"
                       :formatter="formatterTypeName"
                       min-width="100">
      </el-table-column>
      <el-table-column align="center"
                       prop="createTime"
                       label="发布时间"
                       min-width="120"
                       :formatter="formatterDate">
      </el-table-column>
      <el-table-column align="center"
                       prop="isTop"
                       label="是否置顶"
                       min-width="50"
                       :formatter="formatterIsTop">
      </el-table-column>
      <el-table-column align="center"
                       min-width="100"
                       label="操作">
        <template slot-scope="scope">
          <el-button type="primary"
                     @click="handleEdit(scope.row)">编 辑
          </el-button>
          <el-button type="danger"
                     @click="handleDel(scope.row)">删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <page @getList="_getList"
          :pageTotal="pageTotal"
          ref="page"></page>
    <el-dialog
      title="新增/编辑"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="70%">
      <el-form
               :rules="rules"
               ref="sizeForm"
               label-position="right"
               label-width="85px"
               :model="sizeForm">
        <div class="info"
             :style="{'left': (sizeForm.contentType === 1 ? '70%' : '31%')}">
          <el-form-item label="标题"
                        prop="title">
            <el-input v-model="sizeForm.title"></el-input>
          </el-form-item>
          <el-form-item label="作者/来源"
                        prop="sourceName">
            <el-input v-model="sizeForm.sourceName"></el-input>
          </el-form-item>
          <el-form-item label="摘要"
                        prop="summary">
            <el-input style="width: 90%;"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入摘要..."
                      v-model="sizeForm.summary"></el-input>
          </el-form-item>
          <el-form-item label="是否置顶"
                        prop="isTop">
            <el-checkbox v-model="sizeForm.isTop"></el-checkbox>
          </el-form-item>
          <el-form-item label="封面图"
                        prop="imageUrl">
            <el-upload class="avatar-uploader"
                       :action="uploadImgUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeAvatarUpload">
              <img v-if="sizeForm.imageUrl"
                   :src="sizeForm.imageUrl"
                   class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="内容类型"
                        prop="contentType">
            <el-select v-model="sizeForm.contentType"
                       placeholder="请选择">
              <el-option v-for="item in typeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="阅读次数" class="is-required"
                        prop="readTimes">
            <el-input v-model.number="sizeForm.readTimes"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"
                       @click="addDiseaseType">新增病种类型
            </el-button>
            <el-table :data="sizeForm.jsonData"
                      style="width: 100%">
              <el-table-column align="center"
                               prop="name"
                               label="名称">
              </el-table-column>
              <el-table-column align="center"
                               prop="itemNames"
                               label="类型">
              </el-table-column>
              <el-table-column align="center"
                               min-width="100"
                               label="操作">
                <template slot-scope="scope">
                  <el-button size="mini"
                             type="danger"
                             @click="deleteRow(scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item prop="content" v-if="sizeForm.contentType === 1">
            <div>
              <vue-neditor-wrap
                :destroy="true"
                v-model="sizeForm.content"
                :config="myConfig"></vue-neditor-wrap>
            </div>

          </el-form-item>

          <el-form-item v-if="sizeForm.contentType === 2"
                        label="外链URL"
                        prop="linkUrl">
            <el-input v-model="sizeForm.linkUrl"></el-input>
          </el-form-item>

        </div>
      </el-form>
      <p align="center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary"
                   @click="handleSave('sizeForm')">确 定
        </el-button>
      </p>
    </el-dialog>

    <el-dialog title="病种选择"
               :visible.sync="dialogFormVisible">
      <el-form :model="drugDiseaseType">
        <el-form-item label="病种">
          <el-select v-model="drugDiseaseType.id"
                     placeholder="请选择"
                     @change="initDrugDiseaseTypeItem">
            <el-option v-for="item in drugDiseaseTypeList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="drugDiseaseType.drugDiseaseTypeItem"
                     placeholder="请选择"
                     multiple>
            <el-option v-for="item in drugDiseaseTypeListItem"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveDrugDiseaseType">确 定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Page from '@/base/page/page'
import {mapGetters} from "vuex";
import VueNeditorWrap from "vue-neditor-wrap";

export default {
  name: "diseaseScienceList",
  data() {
    return {
      myConfig: {
        // 你的UEditor资源存放的路径,相对于打包后的index.html
        UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: '418',
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 关闭自动保存
        enableAutoSave: false,
        scaleEnabled: true
      },
      dialogFormVisible: false,
      resetKey: true,
      tableData: [],
      pageTotal: 0,       //总条数
      dialogVisible: false,
      fullscreen: true,
      param: {
        type: 4,
        searchCondition: ''
      },
      labelPosition: 'right',
      uploadImgUrl: this.api.file.uploadImage,
      sizeForm: {
        title: '',
        imageUrl: '',
        type: '',
        contentType: 2,
        content: '',
        linkUrl: '',
        // author: '',
        sourceName: '',
        summary: '',
        isTop: false,
        readTimes: '',
        jsonData: []
      },
      rules: {
        title: [{required: true, message: '标题不能为空', trigger: 'blur'}],
        sourceName: [{required: true, message: '来源/作者不能为空', trigger: 'blur'}],
        imageUrl: [{required: true, message: '封面图不能为空', trigger: 'blur'}],
        contentType: [{required: true, message: '内容类型不能为空', trigger: 'blur'}],
        readTimes: [{required: false, type: 'number', message: '阅读次数必须为数字值', trigger: 'blur'}]
      },
      typeOptions: [
        {
          value: 1,
          label: '富文本'
        },
        {
          value: 2,
          label: '外链URL'
        }
      ],
      allDrugDiseaseTypeList: [],
      allDrugDiseaseTypeListItem: [],
      drugDiseaseTypeList: [],
      drugDiseaseTypeListItem: [],
      drugDiseaseType: {
        id: null,
        name: "",
        drugDiseaseTypeItem: []
      }
    }
  },
  watch: {
    'sizeForm.contentType': function () {
      this.$nextTick(() => {
        if (this.sizeForm.contentType === 2) {
          if (this.$refs.sizeForm.$el.getElementsByTagName("textarea")[1] != undefined) {
            this.$refs.sizeForm.$el.getElementsByTagName("textarea")[1].remove()
          }
        }
      })
    },
    dialogVisible: function () {
      let param = {
        pageIndex: 0,
        pageSize: 100
      };
      if (this.dialogVisible) {
        this.post(this.api.portrait.getDrugDiseaseTypeList, param).then((res) => {
          if (res.data.code === '200') {
            this.drugDiseaseTypeList = res.data.object;
            for (let i = 0; i < this.drugDiseaseTypeList.length; i++) {
              this.allDrugDiseaseTypeList.push(this.drugDiseaseTypeList[i])
            }
          }
        })
      }
      if (!this.dialogVisible) {
        this.$nextTick(() => {
          this.sizeForm = {
            title: '',
            imageUrl: '',
            type: '',
            contentType: 1,
            content: '',
            linkUrl: '',
            sourceName: '',
            summary: '',
            isTop: false,
            readTimes: '',
            jsonData: []
          }
        })
      }
    }
  },
  mounted() {
    this._getList()
  },
  methods: {
    handleQuery() {
      this.page.pageIndex = 0
      this._getList()
    },
    handleAdd() {
      this.sizeForm.type = this.param.type;
      this.dialogVisible = true
    },
    addDiseaseType() {
      this.drugDiseaseType = {
        id: null,
        name: "",
        drugDiseaseTypeItem: []
      };
      this.drugDiseaseTypeList = [];
      let dataList = this.sizeForm.jsonData;
      for (let i = 0; i < this.allDrugDiseaseTypeList.length; i++) {
        let isAdd = false;
        for (let j = 0; j < dataList.length; j++) {
          if (dataList[j].id === this.allDrugDiseaseTypeList[i].id) {
            isAdd = true;
            break;
          }
        }
        if (!isAdd) {
          this.drugDiseaseTypeList.push(this.allDrugDiseaseTypeList[i]);
        }
      }
      this.dialogFormVisible = true;
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.ajax({
        type: this.api.informationDetail.type,
        url: this.api.informationDetail.url,
        data: {id: row.id},
        success: (data) => {
          this.sizeForm = data.object;
          this.sizeForm.isTop = this.sizeForm.isTop === 1 ? true : false
        },
        error: (data) => {
          this.$Message.error(data.message);
        }
      })
    },
    deleteRow(row) {
      for (let i = 0; i < this.sizeForm.jsonData.length; i++) {
        if (this.sizeForm.jsonData[i].id === row.id) {
          this.sizeForm.jsonData.splice(i, 1);
          break;
        }
      }
    },
    initDrugDiseaseTypeItem(drugDiseaseTypeId) {
      this.post(this.api.portrait.getDrugDiseaseTypeItemList, {id: drugDiseaseTypeId}).then((res) => {
        if (res.data.code === '200') {
          this.drugDiseaseTypeListItem = res.data.object;
        }
      })
    },
    handleDel(row) {
      this.$confirm('您确认删除该信息？')
        .then(_ => {
          this.ajax({
            type: this.api.informationDel.type,
            url: this.api.informationDel.url,
            data: {id: row.id},
            success: (data) => {
              this.$message.success('删除成功!');
              this._getList()
            },
            error: (data) => {
              this.$Message.error(data.message);
            }
          })
        })
        .catch(_ => {
        });
    },
    _getList() {
      this.ajax({
        type: this.api.informationList.type,
        url: this.api.informationList.url,
        data: Object.assign({}, this.page, this.param),
        success: (data) => {
          this.tableData = data.object
          this.pageTotal = data.totalNum
        },
        error: (data) => {
          this.$Message.error(data.message);
        }
      })
    },
    formatterDate(row) {
      return this.commonFunction.timestampFormat(new Date(row.createTime), 'yyyy-MM-dd hh:mm:ss')
    },
    formatterIsTop(row) {
      let isTop = ["否", "是"];
      return isTop[row.isTop]
    },
    formatterTypeName(row) {
      if (row.informationTypeDto != null) {
        return row.informationTypeDto.informationTypeName
      }
    },
    catchData: function (html) {
      this.sizeForm.content = html
    },
    handleAvatarSuccess(res) {
      this.sizeForm.imageUrl = res.url;
    },
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isLt10M;
    },
    handleSave(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.sizeForm.isTop) {
            this.sizeForm.isTop = 1
          } else {
            this.sizeForm.isTop = 0
          }
          this.post(this.api.informationSave.uploadInfo, this.sizeForm).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                showClose: true,
                message: "保存成功",
                type: 'success'
              });
              this.dialogVisible = false;
              this._getList()
            } else {
              this.$message({
                showClose: true,
                message: res.data.message,
                type: 'error'
              })
            }
          })
        }
      })
    },
    saveDrugDiseaseType(form) {
      let data = this.drugDiseaseType;
      if (!data.id) {
        this.$message.error('请选择病种');
        return;
      }

      for (let i = 0; i < this.drugDiseaseTypeList.length; i++) {
        if (this.drugDiseaseTypeList[i].id === data.id) {
          data.name = this.drugDiseaseTypeList[i].name;
          break;
        }
      }
      let items = data.drugDiseaseTypeItem;
      if (items == null || items.length == 0) {
        this.$message.error('请选择类型');
        return;
      }
      let type = "";
      for (let i = 0; i < this.drugDiseaseTypeListItem.length; i++) {
        for (let j = 0; j < items.length; j++) {
          if (this.drugDiseaseTypeListItem[i].id === items[j]) {
            type += this.drugDiseaseTypeListItem[i].name + "/";
          }
        }
      }
      data.itemNames = type;
      this.sizeForm.jsonData.push(data);
      this.dialogFormVisible = false;
    },
    cancel() {
      this.dialogVisible = false;
      this._getList()
    }
  },
  computed: {
    ...mapGetters([
      'page'
    ])
  },
  components: {
    Page,
    VueNeditorWrap
  }
}
</script>
<style scoped lang="scss" type="text/scss" rel="stylesheet/scss">

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #606266;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 98px;
  height: 98px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}


</style>
